package com.jasperframework.boot.common.utils;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
  * <p>  </p>
  *
  * @site https://miliqkdoc.motopa.cn/
  * @author daizhao
  * @date 2022/12/12 12:12
  */
public class PaddingUtil {

    public static void main(String[] args) throws Exception {
        String input = "12345678"; // 需要进行填充的字符串
        int blockSize = 4; // 块大小

        // 将字符串转换为字节数组
        byte[] inputData = input.getBytes(StandardCharsets.UTF_8);

        // 计算块大小的字节数
        int blockSizeBytes = blockSize * 4;

        // 计算需要填充的字节数
        int nPaddingBytes = blockSizeBytes - inputData.length % blockSizeBytes;

        // 创建填充字节
        List<Byte> paddingBytes = new ArrayList<>();
        for (int i = 0; i < nPaddingBytes; i++) {
            paddingBytes.add((byte) nPaddingBytes);
        }

        // 创建填充字节数组
        byte[] paddingData = new byte[nPaddingBytes];
        for (int i = 0; i < nPaddingBytes; i++) {
            paddingData[i] = paddingBytes.get(i);
        }

        // 添加填充字节
        byte[] paddedData = new byte[inputData.length + nPaddingBytes];
        System.arraycopy(inputData, 0, paddedData, 0, inputData.length);
        System.arraycopy(paddingData, 0, paddedData, inputData.length, nPaddingBytes);
        System.out.println("补位后的字节数组：" + byteArrayToHexString(paddedData));

        // 将字节数组转换为字符串
        String paddedString = new String(paddedData, StandardCharsets.UTF_8);
        System.out.println("补位后的字符串：" + paddedString);
    }

    // 辅助方法：将字节数组转换为十六进制字符串表示
    private static String byteArrayToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X", b));
        }
        return sb.toString();
    }
}
